//
//  PopViewUtil.swift
//  PaiPaiHappy
//
//  Created by MaiTian on 2021/7/8.
//

import UIKit

public class AlertUtil: NSObject {
    /** 基础弹框
     title 标题
     msg 内容
     leftTitle 左边按钮名称
     rightTitle 右边按钮名称
     isAutoDissMiss 点击背景是否消失
     leftHandler 左边按钮事件
     rightHandler 右边按钮事件
     backgroundHandler 背景事件
     let alertVC = PopupController()
     */

    public static func alert(title: String? = nil,
                             msg: String? = nil,
                             leftTitle: String? = "取消",
                             rightTitle: String? = "确定",
                             centerView: UIView? = nil,
                             isAutoDissMiss: Bool? = nil,
                             leftHandler: (() -> Void)? = nil,
                             rightHandler: (() -> Void)? = nil,
                             backgroundHandler: (() -> Void)? = nil) {
        let alertVC = PopupController()
        alertVC.alert(title: title,
                      msg: msg,
                      leftTitle: leftTitle,
                      rightTitle: rightTitle,
                      centerView: centerView,
                      isAutoDissMiss: isAutoDissMiss,
                      leftHandler: leftHandler,
                      rightHandler: rightHandler,
                      backgroundHandler: backgroundHandler)
        
    }
}

class PopupController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .hex(0x000000, alpha: 0.4)
    }
}

extension PopupController {
    func alert(title: String?,
               msg: String?,
               leftTitle: String?,
               rightTitle: String?,
               centerView: UIView?,
               isAutoDissMiss: Bool?,
               leftHandler: (() -> Void)?,
               rightHandler: (() -> Void)?,
               backgroundHandler: (() -> Void)?) {
        show()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            var model = AlertMode()
            model.title = title ?? ""
            model.msg = msg ?? ""
            model.leftTitle = leftTitle ?? ""
            model.rightTitle = rightTitle ?? ""
            let alertView = AlertView()
            alertView.customView = centerView
            alertView.model = model
            let popView = PopupView(containerView: self.view, contentView: alertView)
            popView.isDismissible = isAutoDissMiss ?? true
            popView.displayPopupView(completion: nil)
            popView.backgroundView.color = .clear
            popView.didDismissCallback = { [weak self] in
                self?.dismiss(animated: false, completion: nil)
                if alertView.selectIndex == 0 {
                    leftHandler?()
                } else if alertView.selectIndex == 1 {
                    leftHandler?()
                } else if alertView.selectIndex == 2 {
                    rightHandler?()
                } else {
                    backgroundHandler?()
                }
            }
        }
    }
    
    private func show() {
        let currentVC = UIApplication.shared.currentVC
        modalPresentationStyle = .overFullScreen
        currentVC?.present(self, animated: false, completion: nil)
    }
}

public class AlertView: UIView {
    var selectIndex: Int = -1
    
    /** 自定义view */
    var customView: UIView?
    
    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        layer.cornerRadius = 8.adapter
        layer.masksToBounds = true
        setupLayout()
    }
    
    // 标题
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.font = .font(16)
        lab.textColor = .hex(0x333333)
        lab.textAlignment = .center
        return lab
    }()
    
    // 内容
    lazy var contentLab: UITextView = {
        let lab = UITextView()
        lab.backgroundColor = .white
        lab.textAlignment = .center
        lab.font = .font(14)
        lab.textColor = .hex(0x666666)
        lab.isEditable = false
        lab.contentInset = UIEdgeInsets(y: 5.adapter)
        return lab
    }()
    
    // 中间按钮
    lazy var centerBtn: UIButton = {
        let btn = UIButton()
        btn.layer.cornerRadius = 22.adapter
        btn.titleLabel?.font = .font(14)
        btn.setTitleColor(.hex(0x333333), for: .normal)
        btn.backgroundColor = .hex(0xF7D54A)
        btn.addTarget(self, action: #selector(centerBtnClick), for: UIControl.Event.touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    // 左边按钮
    lazy var leftBtn: UIButton = {
        let btn = UIButton()
        btn.layer.cornerRadius = 20.adapter
        btn.titleLabel?.font = .font(14)
        btn.setTitleColor(.hex(0x333333), for: .normal)
        btn.backgroundColor = .hex(0xF5F5F5)
        btn.addTarget(self, action: #selector(leftBtnClick), for: UIControl.Event.touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    // 右边按钮
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.layer.cornerRadius = 20.adapter
        btn.titleLabel?.font = .font(14)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = .hex(0x488FFF)
        btn.addTarget(self, action: #selector(rightBtnClick), for: UIControl.Event.touchUpInside)
        btn.isHidden = true
        return btn
    }()
    
    @objc private func centerBtnClick() {
        selectIndex = 0
        alertView()?.dismissPopupView(completion: nil)
    }
    
    @objc private func leftBtnClick() {
        selectIndex = 1
        alertView()?.dismissPopupView(completion: nil)
    }
    
    @objc private func rightBtnClick() {
        selectIndex = 2
        alertView()?.dismissPopupView(completion: nil)
    }
    
    private func setupLayout() {
        frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - 146.adapter/2, width: 296.adapter, height: 146.adapter)
        addSubview(titleLab)
        addSubview(contentLab)
        addSubview(centerBtn)
        addSubview(leftBtn)
        addSubview(rightBtn)
        
        titleLab.centerX(bounds.width/2).top(24.adapter).width(222.adapter)
        contentLab.centerX_offsetTop(titleLab, x: 18.adapter).width(234.adapter)
        centerBtn.centerX(titleLab.center.x).bottom(bounds.height-24.adapter).width(232.adapter).height(44.adapter)
        leftBtn.left(20.adapter).bottom(bounds.height-24.adapter).width(122.adapter).height(40.adapter)
        rightBtn.right(bounds.width-20.adapter).width_height(leftBtn).bottom(leftBtn.frame.maxY)
        
    }
    
    var model: AlertMode! {
        didSet {
            guard let md = model else {
                return
            }
            titleLab.text = md.title
            
            contentLab.text = md.msg
            
            // 标题高度
            let titleHeight = NSAttributedString(string: md.title, attributes: [.font : titleLab.font!]).height(maxWidth: 222.adapter)
            
            // 内容高度
            let contentHeight = NSAttributedString(string: md.msg, attributes: [.font : contentLab.font!]).height(maxWidth: 234.adapter, maxHeight: UIScreen.height - 130.adapter - titleHeight - UIScreen.safeAreaInsets.vertical - 100.h) + 10.adapter
            
            
            titleLab.height(titleHeight)
            contentLab.height(contentHeight)
            
            // 只有title
            if md.title.isEmpty == false, md.msg.isEmpty == true {
                
                if titleHeight < 24.adapter {
                    frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - 146.adapter/2, width: 296.adapter, height: 146.adapter)
                } else {
                    frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - (112.adapter + titleHeight + 4.adapter)/2, width: 296.adapter, height: 112.adapter + titleHeight + 4.adapter)
                }
            } else if md.title.isEmpty == true, md.msg.isEmpty == false {
                contentLab.update(type: .minY(titleLab.frame.minY, .height))
                
                frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - (124.adapter + contentHeight)/2, width: 296.adapter, height: 124.adapter + contentHeight)
                
            } else if md.title.isEmpty == false, model.msg.isEmpty == false {
                contentLab.update(type: .minY(titleLab.frame.maxY+18.adapter, .height))
                frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - (130.adapter + contentHeight + titleHeight)/2, width: 296.adapter, height: 130.adapter + contentHeight + titleHeight)
            }
            
            if customView != nil {
                titleLab.isHidden = true
                contentLab.isHidden = true
                customView?.layoutIfNeeded()
                addSubview(customView!)
                if (customView?.frame.width ?? 0) <= 264.adapter {
                    frame = CGRect(x: UIScreen.width/2 - 296.adapter/2, y: UIScreen.height/2 - (108.adapter + customView!.frame.size.height)/2, width: 296.adapter, height: 108.adapter + customView!.frame.size.height)
                    customView?.frame = CGRect(x: 296.adapter/2 - customView!.frame.size.width/2, y: 24.adapter, width: customView!.frame.size.width, height: customView!.frame.size.height)
                } else {
                    frame = CGRect(x: UIScreen.width/2 - (32.adapter + customView!.frame.size.width)/2, y: UIScreen.height/2 - (108.adapter + customView!.frame.size.height)/2, width: 32.adapter + customView!.frame.size.width, height: 108.adapter + customView!.frame.size.height)
                    
                    customView?.frame = CGRect(x: 16.adapter, y: 24.adapter, width: customView!.frame.size.width, height: customView!.frame.size.height)
                }
            }
            
            if md.leftTitle.isEmpty == false, md.rightTitle.isEmpty == true {
                centerBtn.isHidden = false
                leftBtn.isHidden = true
                rightBtn.isHidden = true
                centerBtn.setTitle(md.leftTitle, for: .normal)
            } else if md.leftTitle.isEmpty == true, md.rightTitle.isEmpty == false {
                centerBtn.isHidden = false
                leftBtn.isHidden = true
                rightBtn.isHidden = true
                centerBtn.setTitle(md.rightTitle, for: .normal)
            } else if md.leftTitle.isEmpty == false, md.rightTitle.isEmpty == false {
                centerBtn.isHidden = true
                leftBtn.isHidden = false
                rightBtn.isHidden = false
                leftBtn.setTitle(md.leftTitle, for: .normal)
                rightBtn.setTitle(md.rightTitle, for: .normal)
            }
            leftBtn.update(type: .maxY(bounds.height-24.adapter, .height))
            rightBtn.update(type: .maxY(leftBtn.frame.maxY, .height))
            centerBtn.update(type: .maxY(leftBtn.frame.maxY, .height))
        }
    }
}

struct AlertMode {
    var title: String = ""
    var msg: String = ""
    var leftTitle: String = ""
    var rightTitle: String = ""
}
